package hos.task;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>Title: PagingTaskManager </p>
 * <p>Description: 任务管理类 </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2023-02-06 8:47
 */
public class PagingTaskManager {

    private final Map<Object, PagingTask<?>> taskMap = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    public <T> PagingTask<T> get(Object key, Auto.AutoPaging<T> autoPaging) {
        PagingTask<?> pagingTask = get(key);
        if (pagingTask != null) {
            return (PagingTask<T>) pagingTask;
        }
        PagingTask<T> task = new PagingTask<>(autoPaging);
        taskMap.put(key, task);
        return task;
    }

    @SuppressWarnings("unchecked")
    public <T> PagingTask<T> get(Object key, PagingRefresh<T> pagingRefresh) {
        PagingTask<?> pagingTask = get(key);
        if (pagingTask != null) {
            return (PagingTask<T>) pagingTask;
        }
        PagingTask<T> task = new PagingTask<>(pagingRefresh);
        taskMap.put(key, task);
        return task;
    }

    @SuppressWarnings("unchecked")
    public <T> PagingTask<T> get(Object key, PagingTask<T> task) {
        PagingTask<?> pagingTask = get(key);
        if (pagingTask != null) {
            return (PagingTask<T>) pagingTask;
        }
        taskMap.put(key, task);
        return task;
    }

    @SuppressWarnings("unchecked")
    public <T> PagingTask<T> get(Object key) {
        if (!taskMap.containsKey(key)) {
            return null;
        }
        PagingTask<?> pagingTask = taskMap.get(key);
        if (pagingTask != null) {
            return (PagingTask<T>) pagingTask;
        }
        return null;
    }

    /**
     * 判断是否存在。
     */
    public boolean exists(Object tag) {
        return taskMap.containsKey(tag);
    }

    /**
     * 移除
     */
    public void remove(Object... tags) {
        if (tags == null) {
            return;
        }
        for (Object tag : tags) {
            if (!taskMap.containsKey(tag)) {
                continue;
            }
            PagingTask<?> task = taskMap.get(tag);
            if (task != null) {
                task.dispose();
                taskMap.remove(tag);
            }
        }
    }

    /**
     * 释放
     */
    public void dispose() {
        Set<Object> keySet = taskMap.keySet();
        for (Object key : keySet) {
            PagingTask<?> task = taskMap.get(key);
            if (task != null) {
                task.dispose();
            }
        }
        taskMap.clear();
    }
}
